
//
//  UIColor+Extension.swift
//  HotNews
//
//  Created by yang on 2017/9/23.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import Foundation

extension UIColor
{
    // MARK: 产生随机色
    class func randomColor() -> UIColor
    {
        let red = CGFloat(arc4random_uniform(256))/255.0
        let green = CGFloat(arc4random_uniform(256))/255.0
        let blue = CGFloat(arc4random_uniform(256))/255.0
        let color = UIColor(red: red, green: green, blue: blue, alpha: 1)
        return color
    }

    // MARK: 十六进制颜色
    class func hexColor(hex: __uint32_t) -> UIColor
    {
        let red = CGFloat((hex & 0xff0000) >> 16)
        let green = CGFloat((hex & 0x00ff00) >> 8)
        let blue = CGFloat((hex & 0x0000ff))
        let color = UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: 1)
        return color
    }
    
    // MARK: 字符串颜色
    class func hexStringColor(hexString: String) -> UIColor
    {
        var cString = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
        if cString.hasPrefix("#")
        {
            let range = (cString as NSString).range(of: "#")
            cString = (cString as NSString).substring(from: range.length)
        }
        if cString.characters.count != 6
        {
            return UIColor(red: 0, green: 0, blue: 0, alpha: 1)
        }
        let rString = (cString as NSString).substring(with: NSMakeRange(0, 2))
        let gString = (cString as NSString).substring(with: NSMakeRange(2, 2))
        let bString = (cString as NSString).substring(with: NSMakeRange(4, 2))
        var r: CUnsignedInt = 0
        var g: CUnsignedInt = 0
        var b: CUnsignedInt = 0
        Scanner(string: rString).scanHexInt32(&r)
        Scanner(string: gString).scanHexInt32(&g)
        Scanner(string: bString).scanHexInt32(&b)
        return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1)
    }
    
    // MARK: R G B 颜色
    class func RGBColor(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor
    {
        if #available(iOS 10.0, *)
        {
            return UIColor(displayP3Red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: 1)
        }
        else
        {
            return UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: 1)
        }
    }
}
